/*
 * @lc app=leetcode.cn id=166 lang=cpp
 *
 * [166] 分数到小数
 */

// @lc code=start
class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        //高精度除法
        typedef long long  ll;
        if(denominator == 0) return "";

        ll num = numerator, denum = denominator;
        if(num % denum == 0) return to_string(num / denum);
        
        string ans;
        //^异或运算
        if((num < 0)  ^ (denum < 0)) ans += '-';
        
        num = abs(num), denum = abs(denum);

        ans += to_string(num / denum) + ".";
        num = num % denum;

        unordered_map<ll,int> hash;
        while(num){
            hash[num] = ans.size();
            num *= 10;
            ans += to_string(num / denum);
            num %= denum;
            if(hash.count(num)){
                ans = ans.substr(0, hash[num]) + '(' + ans.substr(hash[num]) + ')';
                break;
            }
        }
        return ans;
    }
};
// @lc code=end

